﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using Gift.Model.ENUM;
using System.Text;
using Gift.DAL;
using Gift.Model;
using Gift.Security;


    public partial class admin_product_OpenCard : BaseAdmin
    {
        readonly dalCompany theCompany = new dalCompany();
        readonly DALCardState theCardState = new DALCardState();
        tbCompany oCompany = new tbCompany();
        readonly DALAdminLogin theAdminLogin = new DALAdminLogin();
        readonly DALCardType theCardType = new DALCardType();
        readonly Card theCard = new Card();

        public string isDisplayGMS = "none";

        // Methods
        private void Bind()
        {
            if ((base.Request.QueryString["cid"] != null) && (base.Request.QueryString["action"] != null))
            {
                if (base.Request.QueryString["action"].ToString() == "del")
                {
                    SQLAccess.DoSql("delete from DB_Card where cardid=" + base.Request.QueryString["cid"].ToString() + "");
                }
                base.Response.Write("<script language='javascript'>window.location.href='card.aspx';</script>");
                base.Response.End();
            }
        }
        private void BindProfessionAreaType()
        {
            DataSet dsType = new DataSet();
            DALProfessionAreaType theType = new DALProfessionAreaType();
            if (!string.IsNullOrEmpty(base.CompanyId))
            {
                dsType = theType.GetListByCompanyId(base.CompanyId);
            }
            else
            {
                dsType = theType.GetList(string.Empty);
            }
            if (dsType.Tables.Count > 0)
            {
                this.ddlProfessionAreaType.DataSource = dsType.Tables[0].DefaultView;
                this.ddlProfessionAreaType.DataTextField = "Name";
                this.ddlProfessionAreaType.DataValueField = "Id";
                this.ddlProfessionAreaType.DataBind();
            }
            this.ddlProfessionAreaType.Items.Insert(0, new ListItem("所属专区", ""));
        }


        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = this.ddlCurrentPage.SelectedIndex;
            this.GridViewBind("");
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if ((e.Row.RowType == DataControlRowType.Header) || (e.Row.RowType == DataControlRowType.DataRow))
            {
                CheckBox box = new CheckBox();
                box = (CheckBox)e.Row.FindControl("CheckBox1");

                if (box != null)
                {
                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {

                        if (base.CompanyId == null || (base.CompanyId != null && base.LevelId == "1"))
                        {
                            LinkButton lbOpen = new LinkButton();
                            lbOpen = e.Row.FindControl("lbtnOpen") as LinkButton;
                            if (e.Row.Cells[7].Text == "申请激活中")
                            {
                                lbOpen.Text = "批准激活";
                            }
                            else
                            {
                                lbOpen.Visible = false;
                            }
                            isDisplayGMS = "block";

                            this.ibtnOpenCardCompany.Attributes["display"] = "none";
                        }
                        else
                        {
                            //LinkButton lbEnable = new LinkButton();
                            //lbEnable = e.Row.FindControl("lbtnDisable") as LinkButton;
                            //lbEnable.Visible = false;
                            //LinkButton lbCancel = new LinkButton();
                            //lbCancel = e.Row.FindControl("lbtnCancel") as LinkButton;
                            //lbCancel.Visible = false;

                            LinkButton lbOpen = new LinkButton();
                            lbOpen = e.Row.FindControl("lbtnOpen") as LinkButton;
                            lbOpen.Text = "申请激活";

                            if (e.Row.Cells[7].Text == "已领用未激活")
                            {
                                lbOpen.Visible = true;
                            }
                            else
                            {
                                lbOpen.Visible = false;
                            }
                        }

                        if (base.CompanyId != null && base.LevelId != "1")
                        {
                            e.Row.Cells[10].Visible = false;
                        }



                        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=\"" + e.Row.Style["BACKGROUND-COLOR"] + "\"");
                        e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor=\"#efefef\"");
                    }
                    else if (e.Row.RowType == DataControlRowType.Header)
                    {
                        box.Attributes.Add("onclick", "SelectAll(this.checked)");
                    }
                    //e.Row.Cells[9].Visible = false;
                }
            }
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            GridViewSortDirection = GridViewSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;

            string sqlsort = string.Empty;
            if (GridViewSortDirection == SortDirection.Ascending)
            {
                sqlsort = " order by " + e.SortExpression + " ASC ";
            }
            else
            {
                sqlsort = sqlsort = " order by " + e.SortExpression + " DESC ";
            }
            //sqlsort = "select * from DB_Card";
            this.GridViewBind(sqlsort);
        }

        public SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                    ViewState["sortDirection"] = SortDirection.Ascending;
                return (SortDirection)ViewState["sortDirection"];
            }
            set { ViewState["sortDirection"] = value; }
        }

        private void GridViewBind(string Sqlsort)
        {
            string sStates = string.Empty;

            if (this.ddlStates.SelectedItem.Value != "")
            {
                if (this.ddlStates.SelectedItem.Value == "1")
                {
                    sStates = " and states in (1,5) ";
                }
                else if (this.ddlStates.SelectedItem.Value == "7")
                {
                    sStates = " and  states in (1,5) && convert(varchar(10),getdate(),121) >= convert(varchar(10),starttime,121) && convert(varchar(10),getdate(),121) <=convert(varchar(10),endtime,121) ";
                }
                else
                {
                    sStates = " and states = " + this.ddlStates.SelectedItem.Value;
                }
            }
            string sSort = "ORDER BY cardcode asc ";
            if (Sqlsort != string.Empty)
            {
                sSort = Sqlsort;
            }

            string sqlCount = " select count(1)  ";

            string sqlBefor = "select ROW_NUMBER() OVER (" + sSort + ") AS RowNumber,*,(select [name] from tbCardState where Id = db_card.states) as statesName,convert(varchar(10),starttime,121) + ' 至 ' + convert(varchar(10),endtime,121) as exptime, (select Name from tbCardType where Id = DB_Card.CardTypeId) as CardTypeName"
                          + " ,(select CompanyShortName from tbCompany where Id=DB_Card.companyId  ) + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IICompanyId  ),' ') + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IIICompanyId  ),' ') + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IVCompanyId  ),' ') as companyName"
                           + ", case (select top 1 1 from tbGMS where cardid=DB_Card.cardid) when 1 then '已发' else '未发' end as isSend ";

            if (base.CompanyId != null && base.LevelId == "3")
            {
                tbCompany tempCompaney = theCompany.GetModel(int.Parse(base.CompanyId));
                tbCompany tempUpCompany = theCompany.GetModel(tempCompaney.ParentId);
                if (tempUpCompany != null && tempUpCompany.LevelId == 2)
                {
                    sqlBefor = "select ROW_NUMBER() OVER (" + sSort + ") AS RowNumber,*,(select [name] from tbCardState where Id = db_card.states) as statesName,convert(varchar(10),starttime,121) + ' 至 ' + convert(varchar(10),endtime,121) as exptime, (select Name from tbCardType where Id = DB_Card.CardTypeId) as CardTypeName"
                           + " ,(select CompanyShortName from tbCompany where Id=DB_Card.companyId  ) + '->' +  '' + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IIICompanyId  ),' ') + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IVCompanyId  ),' ') as companyName"
                            + ", case (select top 1 1 from tbGMS where cardid=DB_Card.cardid) when 1 then '已发' else '未发' end as isSend ";
                }
            }
            else if (base.CompanyId != null && base.LevelId == "4")
            {
                tbCompany tempCompaney = theCompany.GetModel(int.Parse(base.CompanyId));
                tbCompany tempUpCompany = theCompany.GetModel(tempCompaney.ParentId);
                if (tempUpCompany != null && tempUpCompany.LevelId == 3)
                {
                    tbCompany tempUpUpCompany = theCompany.GetModel(tempUpCompany.ParentId);
                    if (tempUpUpCompany.LevelId == 2)
                    {
                        sqlBefor = "select ROW_NUMBER() OVER (" + sSort + ") AS RowNumber,*,(select [name] from tbCardState where Id = db_card.states) as statesName,convert(varchar(10),starttime,121) + ' 至 ' + convert(varchar(10),endtime,121) as exptime, (select Name from tbCardType where Id = DB_Card.CardTypeId) as CardTypeName"
                          + " ,(select CompanyShortName from tbCompany where Id=DB_Card.companyId  ) + '->' + '' + '->' + '' + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IVCompanyId  ),' ') as companyName"
                           + ", case (select top 1 1 from tbGMS where cardid=DB_Card.cardid) when 1 then '已发' else '未发' end as isSend ";

                    }
                    else
                    {
                        sqlBefor = "select ROW_NUMBER() OVER (" + sSort + ") AS RowNumber,*,(select [name] from tbCardState where Id = db_card.states) as statesName,convert(varchar(10),starttime,121) + ' 至 ' + convert(varchar(10),endtime,121) as exptime, (select Name from tbCardType where Id = DB_Card.CardTypeId) as CardTypeName"
                          + " ,(select CompanyShortName from tbCompany where Id=DB_Card.companyId  ) + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IICompanyId  ),' ') + '->' + '' + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IVCompanyId  ),' ') as companyName"
                           + ", case (select top 1 1 from tbGMS where cardid=DB_Card.cardid) when 1 then '已发' else '未发' end as isSend ";

                    }
                } if (tempUpCompany != null && tempUpCompany.LevelId == 2)
                {
                    sqlBefor = "select ROW_NUMBER() OVER (" + sSort + ") AS RowNumber,*,(select [name] from tbCardState where Id = db_card.states) as statesName,convert(varchar(10),starttime,121) + ' 至 ' + convert(varchar(10),endtime,121) as exptime, (select Name from tbCardType where Id = DB_Card.CardTypeId) as CardTypeName"
                          + " ,(select CompanyShortName from tbCompany where Id=DB_Card.companyId  ) + '->' + '' + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IIICompanyId  ),' ') + '->' + isnull((select CompanyShortName from tbCompany where Id=DB_Card.IVCompanyId  ),' ') as companyName"
                           + ", case (select top 1 1 from tbGMS where cardid=DB_Card.cardid) when 1 then '已发' else '未发' end as isSend ";
                }
            }

            string sql = " from DB_Card where 1=1 "
                         + sStates;

            if (this.cardcodeFrom.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeFrom.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) >= " + this.cardcodeFrom.Value.Trim() + " ";
                }
                catch
                {

                }
            }
            if (this.cardcodeTo.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeTo.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) <= " + this.cardcodeTo.Value.Trim() + " ";
                }
                catch
                {

                }
            }

            if (base.CompanyId != null && string.IsNullOrEmpty(this.ddlCompany0.SelectedItem.Value))
            {
                sql = sql + string.Format(" and (companyId={0} or IICompanyId={1} or IIICompanyId={2} or IVCompanyId={3})"
                                           , base.CompanyId
                                           , base.CompanyId
                                           , base.CompanyId
                                           , base.CompanyId);
            }
            else if (this.ddlCompany0.SelectedItem.Value.Trim() != "")
            {
                sql = sql + string.Format(" and (companyId={0} or IICompanyId={1} or IIICompanyId={2} or IVCompanyId={3})"
                                           , this.ddlCompany0.SelectedItem.Value.Trim()
                                           , this.ddlCompany0.SelectedItem.Value.Trim()
                                           , this.ddlCompany0.SelectedItem.Value.Trim()
                                           , this.ddlCompany0.SelectedItem.Value.Trim());
            }

            if (this.ddlProfessionAreaType.SelectedItem.Value != "")
            {
                sql = sql + " and CardTypeId in(select id from tbCardType where ProfessionAreaTypeId = " + this.ddlProfessionAreaType.SelectedItem.Value + ")";
            }
            if (!string.IsNullOrEmpty(this.ddlCardType.SelectedItem.Value))
            {
                sql = sql + " and CardTypeId = " + this.ddlCardType.SelectedItem.Value;
            }

            sql = sql + " and publishWay='" + this.ddlPublishWay.SelectedItem.Value + "'";
            sqlCount = sqlCount + sql;
            sql = sqlBefor + sql;

            DataTable dtRowCount = SQLAccess.GreatDs(sqlCount).Tables[0];

            int iRowCount = 0;
            int iPageCount = 0;
            if (dtRowCount.Rows.Count > 0)
            {
                iRowCount = int.Parse(dtRowCount.Rows[0][0].ToString());
                if (iRowCount % 500 == 0)
                {
                    iPageCount = iRowCount / 500;
                }
                else
                {
                    iPageCount = iRowCount / 500 + 1;
                }
            }

            sql = string.Format(" SELECT TOP 500 * FROM ( {0} )a  WHERE RowNumber > 500 * ({1})", sql, this.GridView1.PageIndex.ToString());
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];

            this.LblCurrentIndex.Text = "当前第 " + ((this.GridView1.PageIndex + 1)).ToString() + "页";
            this.LblPageCount.Text = "共 " + iPageCount.ToString() + "页";
            this.LblRecordCount.Text = "总计 " + iRowCount.ToString() + "个记录";
            if (table.Rows.Count == 0)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
                this.LblCurrentIndex.Visible = false;
                this.LblPageCount.Visible = false;
                this.LblRecordCount.Visible = false;
            }
            else if (iPageCount == 1)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
                this.LblCurrentIndex.Visible = true;
                this.LblPageCount.Visible = true;
                this.LblRecordCount.Visible = true;
            }
            else
            {

                this.btnFirst.Visible = true;
                this.btnPrev.Visible = true;
                this.btnNext.Visible = true;
                this.btnLast.Visible = true;
                this.LblCurrentIndex.Visible = true;
                this.LblPageCount.Visible = true;
                this.LblRecordCount.Visible = true;
            }
            this.btnFirst.CommandName = "1";
            this.btnPrev.CommandName = (this.GridView1.PageIndex == 0) ? "1" : this.GridView1.PageIndex.ToString();
            this.btnNext.CommandName = (iPageCount == 1) ? iPageCount.ToString() : ((this.GridView1.PageIndex + 2)).ToString();
            this.btnLast.CommandName = iPageCount.ToString();
            this.ddlCurrentPage.Items.Clear();
            for (int i = 1; i <= iPageCount; i++)
            {
                this.ddlCurrentPage.Items.Add(i.ToString());
            }
            if (ddlCurrentPage.Items.Count > 0)
            {
                this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;
            }


            if (Sqlsort == string.Empty)
            {
                table.DefaultView.Sort = "cardcode asc";
            }
            else
            {
                table.DefaultView.Sort = Sqlsort.Replace("order by", "");
            }
            this.GridView1.DataSource = table.DefaultView;
            this.GridView1.DataBind();

            this.SetCompanyMessage();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!base.IsPostBack)
            {

                if (base.CompanyId != null)
                {
                    this.ibtnExport.Visible = false;
                    //this.tdCompany.Visible = false;
                    //this.tdCompanySelect.Visible = false;
                    if (base.LevelId != "1")
                    {
                        this.ddlStates1.Visible = false;
                        this.spanStates1.Visible = false;
                        this.ibtnOpenCard1.Visible = false;

                    }
                    else
                    {
                        this.ibtnOpenCardCompany.Visible = false;
                    }
                    this.FileUpload1.Visible = false;
                    this.btnExport0.Visible = false;
                    this.tdExport.Visible = false;
                }
                else
                {
                    base.ValidateLoginRule(ERule.OpenCardManager);
                    this.ibtnOpenCardCompany.Visible = false;
                }
                this.BindProvenctList();
                this.BindProfessionAreaType();

                this.BindCompanyLevel();
                this.BindCompanyList();
                this.BindCompanyListForDown();
                this.BindCardStates();
                this.BindCardType();
                this.Bind();
                this.GridViewBind("");
            }
        }

        void BindProvenctList()
        {
            DataSet ds = theCompany.GetProvenceList();
            this.ddlProvence.DataTextField = "provence";
            this.ddlProvence.DataValueField = "provence";
            this.ddlProvence.DataSource = ds;
            this.ddlProvence.DataBind();
            this.ddlProvence.Items.Insert(0, new ListItem("请选择省份", ""));

            this.ddlProvence1.DataTextField = "provence";
            this.ddlProvence1.DataValueField = "provence";
            this.ddlProvence1.DataSource = ds;
            this.ddlProvence1.DataBind();
            this.ddlProvence1.Items.Insert(0, new ListItem("请选择省份", ""));
        }

        void BindCompanyLevel()
        {
            DataSet ds = theCompany.GetCompanyLevelList();
            if (base.CompanyId != null)
            {
                ds.Tables[0].DefaultView.RowFilter = " Id >= " + base.LevelId;
            }
            this.ddlLevel.DataTextField = "LevelName";
            this.ddlLevel.DataValueField = "Id";
            this.ddlLevel.DataSource = ds.Tables[0].DefaultView;
            this.ddlLevel.DataBind();
            this.ddlLevel.Items.Insert(0, new ListItem("请选择商家级别...", ""));

            this.ddlLevel1.DataTextField = "LevelName";
            this.ddlLevel1.DataValueField = "Id";
            this.ddlLevel1.DataSource = ds.Tables[0].DefaultView;
            this.ddlLevel1.DataBind();
            this.ddlLevel1.Items.Insert(0, new ListItem("请选择商家级别...", ""));
        }

        protected void PagerButtonClick(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = Convert.ToInt32(((LinkButton)sender).CommandName) - 1;
            this.GridViewBind("");
        }

        protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
        {
            this.GridViewBind("");

        }

        void SetCompanyMessage()
        {
            if (base.CompanyId != null)
            {
                if (base.LevelId != "1")
                {
                    this.tdOpenCardCompanyMessage.InnerText = string.Format("激活说明：您有预付款({0}元),若您申请激活选中卡,如预付款充足,将直接激活选中的卡并扣除相应的预付款,如预付款不足,申请后的卡由上级商家申批激活。", theCompany.GetCompanyMoney(base.CompanyId));
                }
            }
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "open")
            {
                int id = int.Parse(this.GridView1.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString());

                tbCardState oCardState;
                dbCard oCard;
                oCard = theCard.GetModel(id);
                oCardState = theCardState.GetModel(oCard.states);

                if (base.CompanyId == null || (base.CompanyId != null && base.LevelId == "1"))
                {
                    SQLAccess.DoSql("update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                 + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                                 + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                                 + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                                 + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                                  + ",  updatetime='" + DateTime.Now.ToString()
                                 + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddhhmmss")
                                 + ";'  where cardid=" + id.ToString() + " and states = 6");
                }
                else
                    if (base.CompanyId != null)
                    {
                        SQLAccess.DoSql("update DB_Card set states = 6, remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到申请激活中 ,日期:" + DateTime.Now.ToString("yyyyMMddhhmmss")
                                   + ";'  where cardid=" + id.ToString() + " and states = 4");
                    }
                Response.Write("<script language=javascript>alert('修改成功！');</script>");
                this.GridViewBind("");
            }
        }

        protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
        {
            string sStates = "";
            string sql = "select cardcode as 卡号,cardprice as 金额,"
                        + " (select [Name] from tbCardType where id= CardTypeId) as 礼品卡类别,"
                         + " convert(varchar(10),starttime,121) as 专区开始日期, "
                        + " convert(varchar(10),endtime,121) as 专区截止日期,  publishWay as 发行方式,"
                        + " (select Name from tbCompany where Id=DB_Card.companyId  ) + '->' + isnull((select Name from tbCompany where Id=DB_Card.IICompanyId  ),' ') + '->' + isnull((select Name from tbCompany where Id=DB_Card.IIICompanyId  ),' ') + '->' + isnull((select Name from tbCompany where Id=DB_Card.IVCompanyId  ),' ') as 商家 "
                        + " from DB_Card where 1=1 ";

            if (this.ddlStates.SelectedItem.Value != "")
            {
                if (this.ddlStates.SelectedItem.Value == "1")
                {
                    sStates = " and states in (1,5) ";
                }
                else if (this.ddlStates.SelectedItem.Value == "7")
                {
                    sStates = " and  states in (1,5) && convert(varchar(10),getdate(),121) >= convert(varchar(10),starttime,121) && convert(varchar(10),getdate(),121) <=convert(varchar(10),endtime,121) ";
                }
                else
                {
                    sStates = " and states = " + this.ddlStates.SelectedItem.Value;
                }
            }
            sql = sql + sStates;

            if (this.cardcodeFrom.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeFrom.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) >= " + this.cardcodeFrom.Value.Trim() + " ";
                }
                catch
                {
                }
            }
            if (this.cardcodeTo.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeTo.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) <= " + this.cardcodeTo.Value.Trim() + " ";
                }
                catch
                {
                }
            }

            if (base.CompanyId != null && string.IsNullOrEmpty(this.ddlCompany0.SelectedItem.Value))
            {
                sql = sql + string.Format(" and (companyId={0} or IICompanyId={1} or IIICompanyId={2} or IVCompanyId={3})"
                                           , base.CompanyId
                                           , base.CompanyId
                                           , base.CompanyId
                                           , base.CompanyId);
            }
            else if (this.ddlCompany0.SelectedItem.Value.Trim() != "")
            {
                sql = sql + string.Format(" and (companyId={0} or IICompanyId={1} or IIICompanyId={2} or IVCompanyId={3})"
                                           , this.ddlCompany0.SelectedItem.Value.Trim()
                                           , this.ddlCompany0.SelectedItem.Value.Trim()
                                           , this.ddlCompany0.SelectedItem.Value.Trim()
                                           , this.ddlCompany0.SelectedItem.Value.Trim());
            }

            if (this.ddlProfessionAreaType.SelectedItem.Value != "")
            {
                sql = sql + " and CardTypeId in(select id from tbCardType where ProfessionAreaTypeId = " + this.ddlProfessionAreaType.SelectedItem.Value + ")";
            }

            sql = sql + " and publishWay='" + this.ddlPublishWay.SelectedItem.Value + "'";
            sql = sql + " order by cardcode desc";

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];

            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";//设置导出文件的名称
            Gift.Utile.OperateExcel.ExportCSV(table, fileName);

        }

        private string BuildExportHTML(DataTable dt)
        {
            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;
            int pagerecords = 100000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";
            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy-MM-dd") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }

        void BindCompanyList()
        {
            DataTable dt;
            string sWhere = " 1=1 ";
            dt = theCompany.GetList(sWhere).Tables[0];
            if (base.CompanyId != null)
            {
                dt = GetAllCompany(dt, null, int.Parse(base.CompanyId), true);
            }
            else
            {
                dt = GetAllCompany(dt, null, 0, true);
            }

            string sFiler = string.Empty;
            if (this.ddlLevel.SelectedItem.Value != "")
            {
                sFiler = " LevelID = " + this.ddlLevel.SelectedItem.Value;
            }
            if (this.ddlProvence.SelectedItem.Value != "")
            {
                sFiler = sFiler == string.Empty ? " Provence = '" + this.ddlProvence.SelectedItem.Value + "'" : sFiler + " and Provence = '" + this.ddlProvence.SelectedItem.Value + "'";
            }

            dt.DefaultView.RowFilter = sFiler;

            this.ddlCompany0.DataTextField = "Name";
            this.ddlCompany0.DataValueField = "Id";
            this.ddlCompany0.DataSource = dt.DefaultView;
            this.ddlCompany0.DataBind();
            this.ddlCompany0.Items.Insert(0, new ListItem("请选择商家...", ""));
        }

        void BindCompanyListForDown()
        {
            DataTable dt;
            string sWhere = " 1=1 ";
            dt = theCompany.GetList(sWhere).Tables[0];
            if (base.CompanyId != null)
            {
                dt = GetAllCompany(dt, null, int.Parse(base.CompanyId), true);
            }
            else
            {
                dt = GetAllCompany(dt, null, 0, true);
            }

            string sFiler = string.Empty;
            if (this.ddlLevel1.SelectedItem.Value != "")
            {
                sFiler = " LevelID = " + this.ddlLevel1.SelectedItem.Value;
            }
            if (this.ddlProvence1.SelectedItem.Value != "")
            {
                sFiler = sFiler == string.Empty ? " Provence = '" + this.ddlProvence1.SelectedItem.Value + "'" : sFiler + " and Provence = '" + this.ddlProvence1.SelectedItem.Value + "'";
            }
            dt.DefaultView.RowFilter = sFiler;

            this.ddlCompany1.DataTextField = "Name";
            this.ddlCompany1.DataValueField = "Id";
            this.ddlCompany1.DataSource = dt.DefaultView;
            this.ddlCompany1.DataBind();
            this.ddlCompany1.Items.Insert(0, new ListItem("请选择商家...", ""));

        }

        void BindCardStates()
        {
            DataSet dsCard = theCard.GetCardStateList();
            this.ddlStates.DataTextField = "Name";
            this.ddlStates.DataValueField = "Id";
            if (dsCard != null && dsCard.Tables.Count > 0)
            {
                //   dsCard.Tables[0].DefaultView.RowFilter = " Name <> '未发行'";

                this.ddlStates.DataSource = dsCard.Tables[0].DefaultView;
                this.ddlStates.DataBind();
                this.ddlStates.Items.Insert(0, new ListItem("请选择状态...", ""));
                if (!string.IsNullOrEmpty(Request.QueryString["states"]))
                {
                    ddlStates.Items.FindByValue(Request.QueryString["states"]).Selected = true;
                }
            }

            this.ddlStates1.DataTextField = "Name";
            this.ddlStates1.DataValueField = "Id";

            if (dsCard != null && dsCard.Tables.Count > 0)
            {
                dsCard.Tables[0].DefaultView.RowFilter = " Id <> 7";
                this.ddlStates1.DataSource = dsCard.Tables[0].DefaultView;
                this.ddlStates1.DataBind();
            }

        }

        void BindCardType()
        {
            DataSet dsCardType = theCardType.GetList("1=1");
            this.ddlCardType.DataTextField = "Name";
            this.ddlCardType.DataValueField = "Id";
            this.ddlCardType.DataSource = dsCardType;
            this.ddlCardType.DataBind();
            this.ddlCardType.Items.Insert(0, new ListItem("请选择...", ""));

        }

        protected void ibtnUpdateCompany_Click(object sender, ImageClickEventArgs e)
        {
            if (this.ddlCompany1.SelectedItem.Value != "")
            {
                string companyId = "";
                companyId = this.ddlCompany1.SelectedItem.Value;
                for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
                {
                    CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                    if (box.Checked)
                    {
                        oCompany = theCompany.GetModel(int.Parse(companyId));
                        string sUpdateBefor = string.Empty;
                        string sUpdateSql = string.Empty;

                        decimal companyOnSale = theCompany.GetCompanyOnSale(companyId);

                        if (oCompany.LevelId == 2)
                        {
                            decimal companyOnSaleI = theCompany.GetCompanyOnSale(oCompany.ParentId.ToString());
                            sUpdateSql = "  CompanyId = " + oCompany.ParentId + ", CompanyOnSale=" + companyOnSaleI
                                         + " , IICompanyId = " + companyId + ", CompanyIIOnSale=" + companyOnSale
                                         + ", IIICompanyId = NULL ,CompanyIIIOnSale = 1 "
                                          + ", IVCompanyId = NULL ,CompanyIVOnSale = 1 ";
                        }
                        else if (oCompany.LevelId == 3)
                        {
                            tbCompany companyII = theCompany.GetModel(oCompany.ParentId);
                            if (companyII.LevelId == 2)
                            {
                                decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyII.ParentId.ToString());
                                decimal companyOnSaleII = theCompany.GetCompanyOnSale(oCompany.ParentId.ToString());
                                sUpdateSql = "  CompanyId = " + companyII.ParentId + ", CompanyOnSale=" + companyOnSaleI
                                             + " , IICompanyId = " + companyII.Id + ", CompanyIIOnSale=" + companyOnSaleII
                                             + ", IIICompanyId = " + companyId + ", CompanyIIIOnSale=" + companyOnSale
                                              + ", IVCompanyId = NULL ,CompanyIVOnSale = 1 ";
                            }
                            else if (companyII.LevelId == 1)
                            {
                                decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyII.Id.ToString());

                                sUpdateSql = "  CompanyId = " + companyII.Id + ", CompanyOnSale=" + companyOnSaleI
                                             + " , IICompanyId = NULL, CompanyIIOnSale=1"
                                             + ", IIICompanyId = " + companyId + ", CompanyIIIOnSale=" + companyOnSale
                                              + ", IVCompanyId = NULL ,CompanyIVOnSale = 1 ";
                            }
                        }
                        else if (oCompany.LevelId == 4)
                        {
                            tbCompany companyIII = theCompany.GetModel(oCompany.ParentId);

                            if (companyIII.LevelId == 3)
                            {

                                tbCompany companyII = theCompany.GetModel(companyIII.ParentId);
                                decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyII.ParentId.ToString());
                                decimal companyOnSaleII = theCompany.GetCompanyOnSale(companyIII.ParentId.ToString());
                                decimal companyOnSaleIII = theCompany.GetCompanyOnSale(oCompany.ParentId.ToString());
                                sUpdateSql = "  CompanyId = " + companyII.ParentId + ", CompanyOnSale=" + companyOnSaleI
                                             + ",  IICompanyId = " + companyII.Id + ", CompanyIIOnSale=" + companyOnSaleII
                                             + ", IIICompanyId = " + companyIII.Id + ", CompanyIIIOnSale=" + companyOnSaleIII
                                            + ", IVCompanyId = " + companyId + ", CompanyIVOnSale=" + companyOnSale;
                            }
                            else if (companyIII.LevelId == 2)
                            {

                                tbCompany companyI = theCompany.GetModel(companyIII.ParentId);
                                decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyIII.ParentId.ToString());
                                decimal companyOnSaleII = theCompany.GetCompanyOnSale(companyIII.Id.ToString());

                                sUpdateSql = "  CompanyId = " + companyI.Id + ", CompanyOnSale=" + companyOnSaleI
                                             + ",  IICompanyId = " + companyIII.Id + ", CompanyIIOnSale=" + companyOnSaleII
                                             + ", IIICompanyId = NULL, CompanyIIIOnSale=1"
                                            + ", IVCompanyId = " + companyId + ", CompanyIVOnSale=" + companyOnSale;
                            }
                            else if (companyIII.LevelId == 1)
                            {

                                tbCompany companyI = theCompany.GetModel(companyIII.Id);
                                decimal companyOnSaleI = theCompany.GetCompanyOnSale(companyIII.Id.ToString());

                                sUpdateSql = "  CompanyId = " + companyI.Id + ", CompanyOnSale=" + companyOnSaleI
                                             + ",  IICompanyId = NULL, CompanyIIOnSale=1"
                                             + ", IIICompanyId = NULL, CompanyIIIOnSale=1"
                                            + ", IVCompanyId = " + companyId + ", CompanyIVOnSale=" + companyOnSale;
                            }
                        }
                        else if (string.IsNullOrEmpty(base.CompanyId) || base.LevelId == "1")
                        {
                            sUpdateSql = "  CompanyId = " + companyId + ", CompanyOnSale=" + companyOnSale
                                           + ", IICompanyId = NULL ,CompanyIIOnSale = 1 "
                                           + ", IIICompanyId = NULL ,CompanyIIIOnSale = 1 "
                                           + ", IVCompanyId = NULL ,CompanyIVOnSale = 1 ";
                        }
                        if (!string.IsNullOrEmpty(base.CompanyId))
                        {
                            if (base.LevelId == "1")
                            {
                                sUpdateBefor = " IICompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) = 0  then null else IICompanyId end) "
                                                       + ", IIICompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) = 0 then null else IIICompanyId end) "
                                + ", IVCompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) =0 then null else IVCompanyId end) ";
                            }
                            else if (base.LevelId == "2")
                            {
                                sUpdateBefor = " IIICompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) = 0 then null else IIICompanyId end) "
                                + ", IVCompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) =0 then null else IVCompanyId end) ";
                            }
                            else if (base.LevelId == "3")
                            {
                                sUpdateBefor = " IVCompanyId = (case when isnull((select Id from tbCompany where ParentId = " + base.CompanyId + " and id=CompanyId),0) =0 then null else IVCompanyId end) ";
                            }
                            SQLAccess.DoSql("update DB_Card set " + sUpdateBefor + " where cardid=" + this.GridView1.DataKeys[i].Value);
                        }
                        SQLAccess.DoSql("update DB_Card set " + sUpdateSql + ", states=4 where cardid=" + this.GridView1.DataKeys[i].Value + " and states=0");
                        SQLAccess.DoSql("update DB_Card set " + sUpdateSql + ", remark = isnull(remark,'') +'" + base.AdminUser + " 更新了公司为:" + oCompany.Name + ";'   where cardid=" + this.GridView1.DataKeys[i].Value);

                    }
                }
                Response.Write("<script language=javascript>alert('批量更新商家成功！');</script>");
                this.GridViewBind("");
            }
        }

        protected void ibtnOpenCard_Click(object sender, ImageClickEventArgs e)
        {
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    if (base.CompanyId != null)
                    {
                        string sExeSql = string.Empty;
                        decimal dCompanyMoney = theCompany.GetCompanyMoney(base.CompanyId);
                        decimal dOnSale = theCompany.GetCompanyOnSale(base.CompanyId);
                        if (base.LevelId == "2")
                        {
                            tbCompany oCompanyII = theCompany.GetModel(int.Parse(base.CompanyId));
                            tbCompany oCompanyI = theCompany.GetModel(oCompanyII.ParentId);
                            decimal dCompanyOnSaleI = theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                            decimal dCompanyMoneyI = theCompany.GetCompanyMoney(oCompanyI.Id.ToString());

                            sExeSql = " update db_card set states=6 where  cardid=" + this.GridView1.DataKeys[i].Value + " and  states !=1 and states !=2"
                                     + ";update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                + ", OpenAdminId = " + base.AdminUserId
                                 + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                                 + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                                 + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                                 + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                                 + ",  updatetime='" + DateTime.Now.ToString() + "'  where cardprice * " + dOnSale.ToString() + " <= " + dCompanyMoney.ToString()
                                 + " and cardprice * " + dCompanyOnSaleI.ToString() + " <= " + dCompanyMoneyI.ToString()
                                 + " and cardid=" + this.GridView1.DataKeys[i].Value + " and states !=1 and states !=2";
                        }
                        else if (base.LevelId == "3")
                        {
                            tbCompany oCompanyIII = theCompany.GetModel(int.Parse(base.CompanyId));
                            tbCompany oCompanyII = theCompany.GetModel(oCompanyIII.ParentId);
                            tbCompany oCompanyI = null;

                            if (oCompanyII.LevelId == 2)
                            {
                                oCompanyI = theCompany.GetModel(oCompanyII.ParentId);
                            }

                            decimal dCompanyOnSaleI = oCompanyI == null ? theCompany.GetCompanyOnSale(oCompanyII.Id.ToString()) : theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                            decimal dCompanyMoneyI = oCompanyI == null ? theCompany.GetCompanyMoney(oCompanyII.Id.ToString()) : theCompany.GetCompanyMoney(oCompanyI.Id.ToString());
                            decimal dCompanyOnSaleII = oCompanyI == null ? 1 : theCompany.GetCompanyOnSale(oCompanyII.Id.ToString());
                            decimal dCompanyMoneyII = oCompanyI == null ? 0 : theCompany.GetCompanyMoney(oCompanyII.Id.ToString());

                            sExeSql = " update db_card set states=6  where  cardid=" + this.GridView1.DataKeys[i].Value + " and states !=1 and states !=2"
                                     + "; update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                      + ", OpenAdminId = " + base.AdminUserId
                                 + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                                 + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                                 + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                                 + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                                 + ",  updatetime='" + DateTime.Now.ToString() + "'  where cardprice * " + dOnSale.ToString() + " <= " + dCompanyMoney.ToString()
                                 + " and cardprice * " + dCompanyOnSaleI.ToString() + " <= " + dCompanyMoneyI.ToString()
                                 + " and cardprice * " + dCompanyOnSaleII.ToString() + " <= " + dCompanyMoneyII.ToString()
                                 + " and cardid=" + this.GridView1.DataKeys[i].Value + " and states !=1 and states !=2";
                        }
                        else if (base.LevelId == "4")
                        {
                            tbCompany oCompanyIV = theCompany.GetModel(int.Parse(base.CompanyId));
                            tbCompany oCompanyIII = theCompany.GetModel(oCompanyIV.ParentId);

                            tbCompany oCompanyII = null;
                            tbCompany oCompanyI = null;

                            decimal dCompanyOnSaleI = 0;
                            decimal dCompanyMoneyI = 0;
                            decimal dCompanyOnSaleII = 0;
                            decimal dCompanyMoneyII = 0;
                            decimal dCompanyOnSaleIII = 0;
                            decimal dCompanyMoneyIII = 0;

                            if (oCompanyIII.LevelId == 3)
                            {
                                oCompanyII = theCompany.GetModel(oCompanyIII.ParentId);
                                if (oCompanyII.LevelId == 2)
                                {
                                    oCompanyI = theCompany.GetModel(oCompanyII.ParentId);

                                    dCompanyOnSaleI = theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                                    dCompanyMoneyI = theCompany.GetCompanyMoney(oCompanyI.Id.ToString());
                                    dCompanyOnSaleII = theCompany.GetCompanyOnSale(oCompanyII.Id.ToString());
                                    dCompanyMoneyII = theCompany.GetCompanyMoney(oCompanyII.Id.ToString());
                                    dCompanyOnSaleIII = theCompany.GetCompanyOnSale(oCompanyIII.Id.ToString());
                                    dCompanyMoneyIII = theCompany.GetCompanyMoney(oCompanyIII.Id.ToString());
                                }
                                else if (oCompanyII.LevelId == 1)
                                {
                                    oCompanyI = theCompany.GetModel(oCompanyII.Id);

                                    dCompanyOnSaleI = theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                                    dCompanyMoneyI = theCompany.GetCompanyMoney(oCompanyI.Id.ToString());
                                    dCompanyOnSaleII = 1;
                                    dCompanyMoneyII = 0;
                                    dCompanyOnSaleIII = theCompany.GetCompanyOnSale(oCompanyIII.Id.ToString());
                                    dCompanyMoneyIII = theCompany.GetCompanyMoney(oCompanyIII.Id.ToString());
                                }
                            }
                            else if (oCompanyIII.LevelId == 2)
                            {
                                oCompanyII = theCompany.GetModel(oCompanyIII.Id);
                                oCompanyI = theCompany.GetModel(oCompanyII.ParentId);

                                dCompanyOnSaleI = theCompany.GetCompanyOnSale(oCompanyI.Id.ToString());
                                dCompanyMoneyI = theCompany.GetCompanyMoney(oCompanyI.Id.ToString());
                                dCompanyOnSaleII = theCompany.GetCompanyOnSale(oCompanyII.Id.ToString());
                                dCompanyMoneyII = theCompany.GetCompanyMoney(oCompanyII.Id.ToString());
                                dCompanyOnSaleIII = 1;
                                dCompanyMoneyIII = 0;
                            }

                            tbCardState oCardState;
                            dbCard oCard;
                            oCard = theCard.GetModel(int.Parse(this.GridView1.DataKeys[i].Value.ToString()));
                            oCardState = theCardState.GetModel(oCard.states);

                            sExeSql = " update db_card set states=6 " + ",  updatetime='" + DateTime.Now.ToString()
                                 + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到申请激活中 ,日期:" + DateTime.Now.ToString("yyyyMMddhhmmss")
                                   + ";' where cardid=" + this.GridView1.DataKeys[i].Value + " and states !=1 and states !=2"
                                     + "; update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'"
                                 + ", OpenAdminId = " + base.AdminUserId
                                 + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                                 + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                                 + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                                 + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                                 + ",  updatetime='" + DateTime.Now.ToString()
                                 + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到审核通过已激活,日期:" + DateTime.Now.ToString("yyyyMMddhhmmss")
                                 + ";'  where cardprice * " + dOnSale.ToString() + " <= " + dCompanyMoney.ToString()
                                 + " and cardprice * " + dCompanyOnSaleI.ToString() + " <= " + dCompanyMoneyI.ToString()
                                 + " and cardprice * " + dCompanyOnSaleII.ToString() + " <= " + dCompanyMoneyII.ToString()
                                 + " and cardprice * " + dCompanyOnSaleIII.ToString() + " <= " + dCompanyMoneyIII.ToString()
                                 + " and cardid=" + this.GridView1.DataKeys[i].Value + " and states !=1 and states !=2";
                        }
                        if (!string.IsNullOrEmpty(sExeSql))
                        {
                            SQLAccess.DoSql(sExeSql);
                        }

                    }
                }
            }
            Response.Write("<script language=javascript>alert('批量激活成功！');</script>");
            this.GridViewBind("");
        }

        protected void ibtnInport_Click(object sender, ImageClickEventArgs e)
        {
            if (this.FileUpload1.FileContent.Length <= 0)
            {
                Response.Write("<script>alert('请选择要导入的EXCEL文件！')</script>");
                return;
            }
            else
            {
                try
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
                    this.FileUpload1.SaveAs(Server.MapPath("../uploadTempFile/" + fileName));
                    DataTable dtResult = new DataTable();
                    dtResult = Gift.Utile.OperateExcel.InputCSV(Server.MapPath("../uploadTempFile/" + fileName));
                    DataRow[] dr = dtResult.Select();
                    int ss = dtResult.Rows.Count;
                    int rowsnum = dtResult.Rows.Count;
                    if (rowsnum == 0)
                    {
                        Response.Write("<script>alert('Excel表为空表,无数据！')</script>");
                        return;
                    }
                    int iInportSum = 0;

                    for (int i = 0; i < rowsnum; i++)
                    {
                        string cardtypeId = "0";
                        tbCardType oCardType = theCardType.GetModelByName(dr[i][3].ToString());
                        if (oCardType != null)
                        {
                            cardtypeId = oCardType.CardTypeId.ToString();
                        }

                        string cardcode = dr[i][0].ToString();
                        string cardpass = dr[i][1].ToString();
                        string cardprice = dr[i][2].ToString() == "" ? "0" : dr[i][2].ToString();
                        string starttime = dr[i][4].ToString();
                        string endtime = dr[i][5].ToString();
                        string publishWay = dr[i][6].ToString();
                        string companyid = "0";
                        if (dr[i].ItemArray.Length > 6)
                        {
                            tbCompany oCompany = theCompany.GetModelByName(dr[i][6].ToString());
                            if (oCompany != null)
                            {
                                companyid = oCompany.Id.ToString();
                            }
                        }

                        string sql = " if exists(select 1 from DB_Card where cardcode = '" + cardcode + "') "
                                    + " begin "
                                     + " update DB_Card  set cardtypeid = " + cardtypeId
                                     + " ,cardprice = " + cardprice
                                     + " ,starttime = '" + starttime + "'"
                                      + " ,endtime = '" + endtime + "'"
                                       + " ,lasttime = '" + endtime + "'"
                                     + " ,publishWay='" + publishWay + "'"
                                     + ", companyid = " + companyid
                                     + " where cardcode = '" + cardcode + "'"
                                     + " end"
                                     + " else"
                                     + " begin "
                                     + " insert into DB_Card(cardtypeId,cardcode,cardpas,cardprice,starttime,endtime,states,companyid,lasttime,publishWay)"
                                     + " values(" + cardtypeId + ",'" + cardcode + "','" + DESEncrypt.Encrypt(cardpass) + "'," + cardprice + ",'" + starttime + "','" + endtime + "',4," + companyid + ",'" + endtime + "','" + publishWay + "' )"
                                     + " end";
                        SQLAccess.DoSql(sql);
                        iInportSum++;

                    }
                    Response.Write("<script>alert('成功导入" + iInportSum.ToString() + "条礼品卡记录！')</script>");
                    this.Dispose();
                    this.GridViewBind("");
                }
                catch (Exception ex)
                {
                    Response.Write("出错了：" + ex.ToString());
                }
            }

        }

        protected void ibtnExport0_Click(object sender, ImageClickEventArgs e)
        {
            string sql = "select top 0 cardcode as 卡号,cardpas as 密码,cardprice as 金额,"
                      + " (select [Name] from tbCardType where id= CardTypeId) as 礼品卡类别,"
                       + " convert(varchar(10),starttime,121) as 专区开始日期,"
                      + " convert(varchar(10),endtime,121) as 专区截止日期,publishWay as 发行方式 ,'' as 商家 from DB_Card where 1=1 ";


            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];

            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";//设置导出文件的名称
            Gift.Utile.OperateExcel.ExportCSV(table, fileName);
        }

        protected void ibtnOpenCard0_Click(object sender, ImageClickEventArgs e)
        {
            dbCard oCard;

            tbCardState oCardState;
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");

                if (box.Checked)
                {
                    oCard = theCard.GetModel(int.Parse(this.GridView1.DataKeys[i].Value.ToString()));
                    oCardState = theCardState.GetModel(oCard.states);
                    if (this.ddlStates1.SelectedItem.Value == "1")
                    {
                        SQLAccess.DoSql("update DB_Card set states=1,opentime='" + DateTime.Now.ToString() + "'," + "OpenAdminid=" + base.AdminUserId
                                 + ", CompanyOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.CompanyId order by AddDate desc),1)"
                                 + ", CompanyIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IICompanyId order by AddDate desc),1)"
                                 + ", CompanyIIIOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IIICompanyId order by AddDate desc),1)"
                                 + ", CompanyIVOnSale = isnull((select top 1 OnSale from tbCompanyOnSale where CompanyId = db_card.IVCompanyId order by AddDate desc),1)"
                                 + ",  updatetime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlStates1.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddhhmmss") + ";'  where cardid=" + this.GridView1.DataKeys[i].Value + " and states!=2 and  states!=1");
                    }
                    else
                    {
                        SQLAccess.DoSql("update DB_Card set states=" + this.ddlStates1.SelectedItem.Value + ",  updatetime='" + DateTime.Now.ToString() + "', remark = isnull(remark,'') +'" + base.AdminUser + "更新状态从" + oCardState.Name + "到" + this.ddlStates1.SelectedItem.Text + ",日期:" + DateTime.Now.ToString("yyyyMMddhhmmss") + ";' where cardid=" + this.GridView1.DataKeys[i].Value + " and states!=2");

                    }
                }
            }
            Response.Write("<script language=javascript>alert('批量更新状态成功！');</script>");
            this.GridViewBind("");
        }


        protected void ibtnStoreOut_Click(object sender, ImageClickEventArgs e)
        {
            if (string.IsNullOrEmpty(this.ddlCompany0.SelectedItem.Value))
            {
                Response.Write("<script language=javascript>alert('请选取商家！');</script>");
                return;
            }
            Response.Redirect("StoreOut.aspx?companyid=" + this.ddlCompany0.SelectedItem.Value + "&cardCodeFrom=" + this.cardcodeFrom.Value + "&cardCodeTo=" + this.cardcodeTo.Value);

        }

        protected void ddlLevel_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCompanyList();
        }

        protected void ddlProvence_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCompanyList();
        }


        protected void ddlProvence1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCompanyListForDown();
        }

        protected void ddlLevel1_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindCompanyListForDown();
        }

        protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void ibtnReset_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("OpenCard.aspx");
        }



    }
